const { Controller } = require('egg');
const url = require('url');
const superagent = require('superagent');
const cheerio = require('cheerio');

function resolveHtml(targetUrl) {
  return new Promise(resolve => {
    const defaultUrl = '';// 自己默认的图片链接
    superagent.get(targetUrl).end(function(err, content) {
      const $ = cheerio.load(content.text);
      let iconUrl = $("link[rel*='icon']").eq(0).attr('href'); // 获得 icon 的链接
      console.log(content.text);
      // 如果 iconUrl 存在 还需要判断其是否是相对位置
      if (iconUrl) {
        // 如果不存在 'http'
        if (iconUrl.indexOf('http') === -1) {
          // 判断是否为相对路径或根路径
          if (iconUrl.charAt(0) === '/') {
            const urlString = url.parse(targetUrl);
            iconUrl = `${urlString.protocol}//${urlString.host}${iconUrl}`;
          } else {
            iconUrl = targetUrl + '/' + iconUrl;
          }
        }
        resolve({
          icon: iconUrl,
          title: $('title').text(),
        });
      } else {
        resolve(defaultUrl);
      }
    });
  });
}

class AppController extends Controller {
  async type() {
    const type = await this.ctx.service.app.type();

    this.ctx.body = {
      code: 1,
      data: type,
    };
  }

  async websiteInfo() {
    const { ctx } = this;
    const urlInfo = url.parse(ctx.query.url, true);
    const website = await resolveHtml(ctx.query.url);
    console.log(website);
    ctx.body = {
      code: 1,
      data: {
        hostname: urlInfo.protocol + '://' + urlInfo.hostname,
        ...website,
      },
    };
  }

  async createWebsite() {
    const { ctx } = this;
    const body = ctx.request.body;
    try {
      await this.ctx.service.app.add(body);
      ctx.body = {
        code: 1,
        message: '添加成功',
      };
    } catch (e) {
      ctx.throw(422, {
        code: 0,
        message: '添加失败',
      });
    }
  }

  async websiteList() {
    const { ctx } = this;
    const query = ctx.query;
    const data = await this.ctx.service.app.list(query);
    ctx.body = {
      code: 1,
      data,
    };
  }
}

module.exports = AppController;

